package main

import (
	"MaterialIdentification/svc"
	"github.com/gin-gonic/gin"
	"log/slog"
	"net/http"
	"time"
)

type Logs struct {
	Id            uint
	Username      string
	Name          string
	Phone         string
	Identifynum   int
	Increase      int
	Decrease      int
	Total         int
	Equipment     string
	Operatetime   time.Time
	Mtype         string
	Permissions   string
	Originpicture string
	Resultpicture string
}

type Querydto struct {
	Condition string
	Start     time.Time
	End       time.Time
}

// 查询日志
// 格式：2020-01-18T00:00:00Z
func Getlogs(context *gin.Context) {
	q := Querydto{}
	context.BindJSON(&q)

	var logs []Logs
	if q.Condition == "" && q.Start.IsZero() && q.End.IsZero() {
		err := svc.Db.Find(&logs).Error
		if err != nil {
			slog.Error("数据boom了", "err", err)
			context.JSON(http.StatusOK, NewResp(1, "系统异常"))
			return
		}
		context.JSON(http.StatusOK, NewRespData("无条件查询所有日志成功", logs))
		return

	} else if q.Condition != "" && q.Start.IsZero() && q.End.IsZero() {
		err := svc.Db.Where("username LIKE ? OR name LIKE ? OR phone LIKE ? OR identifynum LIKE ? OR total LIKE ? OR equipment LIKE ? OR mtype LIKE ? OR permissions LIKE ?", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%").Find(&logs).Error
		if err != nil {
			slog.Error("数据boom了", "err", err)
			context.JSON(http.StatusOK, NewResp(1, "系统异常"))
			return
		}
		context.JSON(http.StatusOK, NewRespData("只按搜索框查日志成功", logs))
		return
	} else if q.Condition == "" && !q.Start.IsZero() && !q.End.IsZero() {
		err := svc.Db.Where("operatetime BETWEEN ? AND ?", q.Start, q.End).Find(&logs).Error
		if err != nil {
			slog.Error("数据boom了", "err", err)
			context.JSON(http.StatusOK, NewResp(1, "系统异常"))
			return
		}
		context.JSON(http.StatusOK, NewRespData("只按时间查日志成功", logs))
		return
	} else if q.Condition != "" && !q.Start.IsZero() && !q.End.IsZero() {
		err := svc.Db.Where("username LIKE ? OR name LIKE ? OR phone LIKE ? OR identifynum LIKE ? OR total LIKE ? OR equipment LIKE ? OR mtype LIKE ? OR permissions LIKE ? AND operatetime BETWEEN ? AND ?", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", q.Start, q.End).Find(&logs).Error
		if err != nil {
			slog.Error("数据boom了", "err", err)
			context.JSON(http.StatusOK, NewResp(1, "系统异常"))
			return
		}
		context.JSON(http.StatusOK, NewRespData("综合查询日志成功", logs))
		return
	}
}
